package com.ruoyi.epidemic.web;

import cn.hutool.http.HttpUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.epidemic.domain.TbDetails;
import com.ruoyi.epidemic.domain.TbHistory;
import com.ruoyi.epidemic.service.ITbDetailsService;
import com.ruoyi.epidemic.service.ITbHistoryService;
import com.ruoyi.epidemic.vo.HistoryVo;
import org.apache.tomcat.util.security.MD5Encoder;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.DigestSignatureSpi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyc
 * @createDate 2023/3/21 10:15
 */
@RestController
@RequestMapping("/web/details")
public class DetailsController {

    @Autowired
    private ITbDetailsService detailsService;

    @Autowired
    private ITbHistoryService historyService;

    public String getMD5(String s){
        try  {
            MessageDigest md  =  MessageDigest.getInstance( "MD5" );
            byte[]  messageDigest  =  md.digest(s.getBytes());
            BigInteger no  =  new  BigInteger(1,  messageDigest);
            String  hashText  =  no.toString(16);
            while  (hashText.length()  <  32)  {
                hashText  =    0    +  hashText;
            }
            return  hashText.toUpperCase();
        }  catch  (NoSuchAlgorithmException e)  {
            throw  new  RuntimeException(e);
        }
    }



//    public static void main(String[] args) throws Exception {
//        String url = "http://apitest.ofpay.com/newOnlineOrder.do";
//
//
//        String extendParams = URLEncoder.encode("{\"specialKey\":\"3d86f9d777fb9f6285a730f28d4387ab\"}", "GBK");
//
//        Map<String, String> param = new HashMap<>();
//        param.put("userId", "A08566");
//        param.put("userPws", "4c625b7861a92c7971cd2029c2fd3c4a");
//        param.put("cardId", "101443");
//        param.put("buyNum", "1000");
//        param.put("customerNo", openid);
//        System.out.println(param.get("customerNo"));
//        param.put("orderTime", getHttpResponseJson1.data());
//        param.put("extendParams",extendParams);
//        param.put("spOrderId", getHttpResponseJson1.order_id());
//        param.put("version", "6.0");
//        String md5 = MD5Util.digest(param.get("userId") + param.get("userPws") + param.get("cardId") + param.get("buyNum")
//                + param.get("spOrderId") + param.get("orderTime") + param.get("customerNo") + "OFCARD", "GBK")/*.toUpperCase()*/;
//        param.put("md5Str", md5);
//        System.out.println(SimpleHttpClient.asFireFox().post(url, param, "GBK", 1000000));
//
//
//
//    }
    //获取新冠全国疫情（新浪）数据
    @GetMapping("/xinlang")
    public String thirdParty() throws UnsupportedEncodingException {
        String url = "http://apitest.ofpay.com/newOnlineOrder.do";


        String extendParams = URLEncoder.encode("{\"specialKey\":\"3d86f9d777fb9f6285a730f28d4387ab\"}", "GBK");
        String gbk = URLDecoder.decode(extendParams, "GBK");
        System.out.println("加密数据:"+extendParams);
        System.out.println("解密后的数据:"+gbk);
        System.out.println(extendParams);
        Map<String, Object> param = new HashMap<>();
        param.put("userId", "A08566");
        param.put("userPws", "4c625b7861a92c7971cd2029c2fd3c4a");
        param.put("cardId", "101443");
        param.put("buyNum", "1000");
        param.put("customerNo", "oLidIxK9-h9Z-vBf6KjNyJtehvGE");
        param.put("orderTime", "20230323140214");
        param.put("extendParams", extendParams);
        param.put("spOrderId", "6889977");
        param.put("version", "6.0");
        String md5 = getMD5(""+param.get("userId") + param.get("userPws") + param.get("cardId") + param.get("buyNum")
                + param.get("spOrderId") + param.get("orderTime") + param.get("customerNo") + "OFCARD");
        param.put("md5Str",md5);
        System.out.println(md5);
        String result = HttpUtil.post("http://apitest.ofpay.com/newOnlineOrder.do",param);
        System.out.println(result);
        return result;
    }

    //获取地图疫情数据
    @GetMapping("/list")
    public AjaxResult list() {
        return detailsService.getList();
    }

    //获取全国确诊人数，累计治愈，累计死亡，境外输入
    @GetMapping("/count")
    public AjaxResult count() {
        TbHistory tbHistory = historyService.selectNewData();

        HistoryVo historyVo = new HistoryVo();
        BeanUtils.copyProperties(tbHistory, historyVo);
        historyVo.setExisting(historyVo.getConfirm() - historyVo.getHeal() - historyVo.getDead());
        return AjaxResult.success(historyVo);
    }

    //获取各个省份确诊人数并排序
    @GetMapping("/countProvince")
    public AjaxResult countWithProvince() {
        return detailsService.countProvince();
    }

    //获取各个省份确诊人数并排序
    @GetMapping("/countDead")
    public AjaxResult countDead() {
        return detailsService.countDead();
    }

    //获取各个省份确诊人数并排序
    @GetMapping("/message")
    public AjaxResult message() {
        return detailsService.message();
    }

    @RequestMapping("/excel")
    public AjaxResult importData(@RequestParam MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelUtil<TbDetails> tbDetailsExcelUtil = new ExcelUtil<>(TbDetails.class);
        List<TbDetails> list = tbDetailsExcelUtil.importExcel(inputStream, 0);
        for (int i = 0; i < list.size(); i++) {
            String city = list.get(i).getCity();
            TbDetails tbDetails = detailsService.selectByCity(city);
            if (tbDetails!=null){
                int i1 = detailsService.updateTbDetails(list.get(i));
            }else {
                int i1 = detailsService.saveDetails(list.get(i));
                if (i1 < 0) {
                    return AjaxResult.error("导入数据错误，请检查文档格式");
                }
            }
        }
        return AjaxResult.success(list);
    }

    //获取每日确诊人数
    @GetMapping("/countDay")
    public AjaxResult countDay() {
        return historyService.countDay();
    }
}
